/** 
    固件版本列表页
*/

import React, { Component } from "react";
import GridTable from '../../../components/display/gridTable';
import { frameWorkList, updateFrameStatus, prefixFile, uploadFrameWork } from "../../../fetch/fetchApi";
import { Button, Input, Row, Col, Select, Divider, Modal, Form, Upload, Icon, message, Tooltip } from 'antd';
const Option = Select.Option;
const FormItem = Form.Item;
const {TextArea} = Input;

let fileNameJsonParmas = {};
class FrameVersion extends Component {
    constructor(props) {
        super(props);
        this.init();
        this.state = {
            data: [],
            pagination: {},
            loading: false,
            visible: false,
        };
    }

    componentDidMount() {
        fileNameJsonParmas = {};
        this.fetch();
    }

    init() {
        this.query = {
            page: 1,
            pagecount: 10,
            status: 0
        };
        this.tableColumns = [
            {
                title: '固件型号',
                dataIndex: 'typeId',
                "key": "typeId"
            }, {
                title: '版本号',
                dataIndex: 'frameWork',
                "key": "frameWork"
            }, {
                title: '设备类型',
                dataIndex: 'typeStr',
                "key": "typeStr",
                className: 'column-nowrap'
            }, {
                title: '版本说明',
                dataIndex: 'info',
                "key": "info",
                className: 'column-nowrap',
                render: (text) => (
                    <Tooltip placement="topLeft" title={text} >
                        {text}
                    </Tooltip>
                )
            }, {
                title: '描述',
                dataIndex: 'desc',
                "key": "desc",
                className: 'column-nowrap',
                render: (text) => (
                    <div>
                        <Tooltip placement="topLeft" title={text} >
                            {text ? (text.length > 20 ? text.substring(0, 20) + "..." : text) : text}
                        </Tooltip>
                    </div>
                )
            }, {
                title: '当前状态',
                dataIndex: 'frameStatusStr',
                "key": "frameStatusStr",
                className: 'column-nowrap'
            }, {
                title: '是否发版',
                dataIndex: 'isReleaseStr',
                "key": "isReleaseStr",
                className: 'column-nowrap'
            }, {
                title: '上传时间',
                dataIndex: 'updateTime',
                "key": "updateTime",
                className: 'column-nowrap'
            }, {
                title: '操作',
                key: 'operation',
                fixed: 'right',
                width: 100,
                render: (text, record) => (
                    <div>
                        {record.isRelease === "0" &&
                            this.props.which === 1 &&
                                record.frameStatus !== "2" &&
                                    <span>
                                        <a href="javascript:void(0);" onClick={(e) => this.updateRelease(record, "1")}>发布</a>
                                        <Divider type="vertical" />
                                        <a href="javascript:void(0);" onClick={(e) => this.updateFrameStatus(record, "2")}>删除</a>
                                        <Divider type="vertical" />
                                    </span>
                        }
                        {record.frameStatus === "0" &&
                            <span>
                                <a href="javascript:void(0);" onClick={(e) => this.updateFrameStatus(record, "1")}>禁用</a>
                            </span>
                        }
                        {record.frameStatus === "1" &&
                            <span>
                                <a href="javascript:void(0);" onClick={(e) => this.updateFrameStatus(record, "0")}>启用</a>
                            </span>
                        }
                        {record.frameStatus === "2" &&
                            <span>--</span>
                        }
                    </div>
                )
            }
        ];

    }

    updateRelease = (record, release) => {
        updateFrameStatus({
            typeId: record.typeId,
            frameWork: record.frameWork,
            status: record.frameStatus,
            isRelease: release
        }).then((data) => {
            if (data.data.code === "200") {
                message.success("操作成功！");
                this.query["page"] = 1;
                this.fetch();
            }
        }).catch((ex) => {
            console.log(ex);
        })
    }

    updateFrameStatus = (record, status) => {
        updateFrameStatus({
            typeId: record.typeId,
            frameWork: record.frameWork,
            status: status,
            isRelease: record.isRelease
        }).then((data) => {
            if (data.data.code === "200") {
                message.success("操作成功！");
                this.query["page"] = 1;
                this.fetch();
            }
        }).catch((ex) => {
            console.log(ex);
        })
    }

    showModal = () => {
        fileNameJsonParmas = {};
        this.setState({
            visible: true,
            textAreaValue: ""
        });
    }

    async findFrameWorkList() {
        return await frameWorkList(this.query);
    }

    typeIdChangeHandle =(e) => {
        this.query["typeId"] = e.target.value;
    }

    versionTypeChangeHandle =(e) => {
        this.query["frameWork"] = e.target.value;
    }

    deviceTypeSelectHandler = (e) => {
        if (e) {
            this.query["type"] = e;
        } else {
            this.query["type"] = null;
        }
    }

    queryHandler = () => {
        this.query["page"] = 1;
        this.fetch();
    }

    fetch = (params = {}) => {
        this.setState({
            loading: true
        });
        this.findFrameWorkList().then((res) => {
            if (!res) {
                return;
            }
            const pagination = this.state.pagination;
            pagination.total = res.data.pageLimit.totalCount;
            pagination.current = params.current || 1;
            pagination.onChange = (page, pageSize) => {
                this.query["page"] = page;
                this.query["pagecount"] = pageSize;
                this.fetch({
                    current: page
                });
            }
            this.setState({
                loading: false,
                data: res.data.data,
                pagination,
            });
        }).catch((ex) => {
            console.log(ex);
        });
    }

    handleOk = (e) => {
        this.setState({
            confirmLoading: true
        })
        uploadFrameWork(fileNameJsonParmas).then((data) => {
            console.log(data);
            if (data.data.code == "200") {
                message.success("提交成功");
            }
            this.setState({
                visible: false,
                confirmLoading: false
            });
        })

    }

    handleCancel = (e) => {
        this.setState({
            visible: false,
        });
    }

    handleIntroChange = (e) => {
        fileNameJsonParmas["info"] = e.target.value;
        this.setState({
            textAreaValue: e.target.value
        });
    }

    handleChange = (info) => {
        let fileList = info.fileList;
        fileList = fileList.slice(-1);
        if (info.file.status === 'done') {
            message.success(`[${info.file.name}]上传成功 `);
        } else if (info.file.status === 'error') {
            message.error(`[${info.file.name}]上传失败`);
        }
        this.setState({
            fileList
        });
    }

    handleStatusSelectChange=(e)=>{
        this.query.status = e||null;
    }

    render() {

        const formItemLayout = {
            labelCol: {
                span: 4
            },
            wrapperCol: {
                span: 16,
                offset: 1
            },
        };
        const props = {
            accept: '.bin',
            name: 'file',
            action: prefixFile + '/uploadFile.do',
            headers: {
                //authorization: 'authorization-text'
            },
            data: {},
            //showUploadList: false,
            multiple: false,
            beforeUpload(file) {
                const fileName = file.name;
                const dataArr = fileName.split("_");
                if (dataArr.length < 8) {
                    message.error("文件格式不对！");
                    return false;
                } else {
                    fileNameJsonParmas["company"] = dataArr[0];
                    fileNameJsonParmas["acDc"] = dataArr[1];
                    fileNameJsonParmas["cmosType"] = dataArr[2];
                    fileNameJsonParmas["typeId"] = dataArr[3];
                    fileNameJsonParmas["stubType"] = dataArr[4];
                    fileNameJsonParmas["date"] = dataArr[5];
                    fileNameJsonParmas["frameWork"] = dataArr[6];
                    fileNameJsonParmas["updateCompany"] = dataArr[7];
                    fileNameJsonParmas["firmwareFileName"] = fileName;

                    props.data.filePath = "chargepoint/firmware/" + dataArr[3] + "/" + fileName;
                }
            },
            onChange: this.handleChange
        };
        const Content = <div className="sc-page-content">
            <div className="page-toolbar">
                <Row gutter={8}>
                    <Col lg={2} xl={2} className="whole-fill">
                        <Input placeholder="固件型号" onChange={this.typeIdChangeHandle}/>
                    </Col>
                    <Col lg={2} xl={2} className="whole-fill">
                        <Input placeholder="版本号" id="versionType" onChange={this.versionTypeChangeHandle}/>
                    </Col>
                    <Col lg={3} xl={3} className="whole-fill">
                        <Select placeholder="设备类型" onChange={this.deviceTypeSelectHandler}>
                            <Option value="">全部</Option>
                            <Option value="ac">交流</Option>
                            <Option value="dc">直流</Option>
                        </Select>
                    </Col>
                    <Col lg={2} xl={2} className="whole-fill">
                        <Select placeholder="状态" defaultValue="0" onChange={this.handleStatusSelectChange}>
                            <Option value="">全部</Option>
                            <Option value="0">正常</Option>
                            <Option value="1">禁用</Option>
                        </Select>
                    </Col>
                    <div  className="button-inlineBlock">
                        <Button type="primary" onClick={this.queryHandler}>查询</Button>
                    </div>
                    <div  className="button-inlineBlock">
                        <Button type="primary" icon="upload" onClick={this.showModal}>上传版本</Button>
                    </div>
                </Row>
            </div>
            <div className="page-panel">
                <GridTable postyle="table-center" data={this.state.data} columns={this.tableColumns} loading={this.state.loading} pagination={this.state.pagination}/>
            </div>
            <Modal title="上传版本" visible={this.state.visible} width="800px" onOk={this.handleOk} onCancel={this.handleCancel} confirmLoading={this.state.confirmLoading}>
              <Form onSubmit={this.handleSubmit} layout="horizontal">
                <FormItem label="选择版本" {...formItemLayout}>
                   <Upload  {...props} fileList={this.state.fileList}>
                    <Button>
                      <Icon type="upload"/> 点击上传
                    </Button>
                  </Upload>
                </FormItem>
                <FormItem label="版本说明" {...formItemLayout}>
                    <TextArea rows={10} onChange={this.handleIntroChange} value={this.state.textAreaValue}/>
                </FormItem>
              </Form>
            </Modal>
        </div>;

        return Content;
    }
}

export default FrameVersion;